package com.icekrvams.billing.listeners

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import com.android.billingclient.api.BillingClient.BillingResponseCode
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.ProductDetails
import com.android.billingclient.api.Purchase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

internal object ListenerHolder {

    private val purchaseConfirmListeners by lazy {
        mutableListOf<PurchaseConfirmListener>()
    }
    private val billingDataResponseListeners by lazy {
        mutableListOf<BillingDataResponseListener>()
    }

    /**
     * 添加 Billing 数据响应结果回调。
     * @param lifecycleOwner 当前 LifecycleOwner，用于在其生命周期结束时，自动移除监听器。
     */
    fun addBillingDataResponseListener(
        billingDataResponseListener: BillingDataResponseListener,
        lifecycleOwner: LifecycleOwner?
    ) {
        billingDataResponseListeners += billingDataResponseListener
        lifecycleOwner?.lifecycle?.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                billingDataResponseListeners -= billingDataResponseListener
            }
        })
    }

    /**
     * 添加商品被确认（或消耗）的监听器。
     * @param lifecycleOwner 当前 LifecycleOwner，用于在其生命周期结束时，自动移除监听器。
     */
    fun addPurchaseConfirmListener(
        purchaseConfirmListener: PurchaseConfirmListener,
        lifecycleOwner: LifecycleOwner?
    ) {
        purchaseConfirmListeners += purchaseConfirmListener
        lifecycleOwner?.lifecycle?.addObserver(object : DefaultLifecycleObserver {
            override fun onDestroy(owner: LifecycleOwner) {
                purchaseConfirmListeners -= purchaseConfirmListener
            }
        })
    }

    /**
     * 商品详细信息查询结果回调。
     */
    suspend fun onQueryProductDetailsResponse(
        billingResult: BillingResult,
        productDetailsList: List<ProductDetails>
    ) {
        withContext(Dispatchers.Main) {
            billingDataResponseListeners.forEach {
                it.onQueryProductDetailsResponse(billingResult, productDetailsList)
            }
        }
    }

    /**
     * 已拥有商品查询结果回调。
     */
    suspend fun onQueryPurchasesResponse(
        billingResult: BillingResult,
        purchaseList: List<Purchase>
    ) {
        withContext(Dispatchers.Main) {
            billingDataResponseListeners.forEach {
                it.onQueryPurchasesResponse(billingResult, purchaseList)
            }
        }
    }

    /**
     * PlayStore 的购买页关闭，回到应用时，常见情况：
     * 1.responseCode == BillingResponseCode.OK 表示完成购买
     * 此时 [purchases] 不会空，但请注意，列表中并非全部已拥有的商品，而是仅包含方才购买的商品。
     *
     * 2.responseCode != BillingResponseCode.OK 取消购买、已拥有该商品等。
     * 此时 [purchases] 为空。
     */
    fun onPurchasesUpdated(
        billingResult: BillingResult,
        purchases: List<Purchase>?
    ) {
        billingDataResponseListeners.forEach {
            it.onPurchasesUpdated(billingResult, purchases)
        }
    }

    /**
     * 商品确认结果。
     * @param purchase 进行确认的商品。
     * @param isSub 是否为订阅商品。
     * @param isConsumable 是否为可消耗性商品。
     *  确认完成，也被认为是订阅完成或购买一次性内购商品完成的标志。
     */
    suspend fun onPurchaseConfirmResult(
        purchase: Purchase,
        isSub: Boolean,
        isConsumable: Boolean,
        billingResult: BillingResult
    ) {
        withContext(Dispatchers.Main) {
            if (isSub) { // 订阅商品确认结果。
                if (isConsumable) throw IllegalStateException("Sub product mustn't be consumable")
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    onSubAcknowledged(purchase)
                } else {
                    onSubAcknowledgeFailed(purchase, billingResult)
                }
                return@withContext
            }
            if (isConsumable) { // 可消耗性内购商品确认结果。
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    onConsumableIapConsumed(purchase)
                } else {
                    onConsumableIapConsumeFailed(purchase, billingResult)
                }
            } else { // 一次性内购商品确认结果。
                if (billingResult.responseCode == BillingResponseCode.OK) {
                    onOneTimeIapAcknowledged(purchase)
                } else {
                    onOneTimeIapAcknowledgeFailed(purchase, billingResult)
                }
            }
        }
    }

    /**
     * 订阅商品被确认完成。
     * @param purchase 被确认的订阅商品。
     */
    private fun onSubAcknowledged(purchase: Purchase) {
        purchaseConfirmListeners.forEach {
            it.onSubAcknowledged(purchase)
        }
    }

    /**
     * 订阅商品确认失败。
     */
    private fun onSubAcknowledgeFailed(
        purchase: Purchase,
        billingResult: BillingResult
    ) {
        purchaseConfirmListeners.forEach {
            it.onSubAcknowledgeFailed(purchase, billingResult)
        }
    }

    /**
     * 一次性内购商品被确认完成。
     * @param purchase 被确认的一次性内购商品。
     */
    private fun onOneTimeIapAcknowledged(purchase: Purchase) {
        purchaseConfirmListeners.forEach {
            it.onOneTimeIapAcknowledged(purchase)
        }
    }

    /**
     * 一次性内购商品确认失败。
     */
    private fun onOneTimeIapAcknowledgeFailed(
        purchase: Purchase,
        billingResult: BillingResult
    ) {
        purchaseConfirmListeners.forEach {
            it.onOneTimeIapAcknowledgeFailed(purchase, billingResult)
        }
    }

    /**
     * 可消耗性内购商品被消耗完成。
     * @param purchase 被消耗的可消耗性内购商品。
     */
    private fun onConsumableIapConsumed(purchase: Purchase) {
        purchaseConfirmListeners.forEach {
            it.onConsumableIapConsumed(purchase)
        }
    }

    /**
     * 可消耗性内购商品确认失败。
     */
    private fun onConsumableIapConsumeFailed(
        purchase: Purchase,
        billingResult: BillingResult
    ) {
        purchaseConfirmListeners.forEach {
            it.onConsumableIapConsumeFailed(purchase, billingResult)
        }
    }
}
